<?php

namespace App\Console\Commands;

use App\Api\Controllers\Config\CqcPayConfigController;
use App\Common\RefundSuccessAction;
use App\Models\Bi\BillLog;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Services\Pay\PayService;
use App\Services\PrintSqlService;
use App\Services\Store\StoreMchService;
use App\Services\Withhold\TL\BillLogService;
use App\Util\ExeclUtil;
use App\Util\LockUtil;
use App\Util\SqlWhenUtil;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class WithholdTLValidCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'withhold:tlvalid {day?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '数据验证';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            ini_set('memory_limit', '512M');
            ini_set('max_execution_time', 0);
            $yesterday = $this->argument('day');
            if (empty($yesterday)) {
                $yesterday = date("Y-m-d", strtotime("-1 day"));
                $yesterdayFile = date("Ymd", strtotime("-1 day"));
            } else {
                $time = $yesterday . " 00:00:00";
                $yesterday = date("Y-m-d", strtotime($time));
                $yesterdayFile = date("Ymd", strtotime($time));
            }
//            $yesterday = "2025-03-04";
            $where = [
                "institution_number" => "0705",
            ];
            $filePath = storage_path(config("withhold.tl.file_path") . '/' . $where["institution_number"] . "_" . $yesterdayFile . ".txt");
            //读取数据
            $f = fopen($filePath, "r");
            if (empty($f)) {
                throw new \Exception("读取失败");
            }
            $total_fee_count = $refund_fee_count = $fee_amount_count = $num = 0;
            $data = [];
            $num = 0;
            while (($line = fgets($f)) !== false) {
                $line = rtrim($line, "\r\n"); // 移除换行符
                //拆分数据
                $array = explode(",", $line);
                $status = $array[10];
                $store_pid = $array[0];
                $out_trade_no = $array[11];

                if ($status == 1) {
                    $total_fee = bcdiv((string)$array[4], "100", 2); //$array[4] / 100;
                } else {
                    $total_fee = "0"; //$array[4] / 100;
                }
                $refund_fee = bcdiv((string)$array[6], "100", 2); //;$array[6] / 100;
                $fee_amount = bcdiv((string)$array[5], "100", 2);

                $total_fee_count = bcadd((string)$total_fee, (string)$total_fee_count, 2);
                $refund_fee_count = bcadd((string)$refund_fee, $refund_fee_count, 2);
                $fee_amount_count = bcadd((string)$fee_amount, $fee_amount_count, 2);
                if ($status == 1) {
                    $num++;
                }
                $uniqkey = $array[11];
                $uniqkeyTime = $array[2];
                //统计金额
                $remark = "";
                //检测订单
                $data[] = [
                    $uniqkey ."-". $uniqkeyTime,
                    $store_pid,
                    $out_trade_no,
                    ($status == 1) ? "支付" : "退款",
                    $total_fee,
                    $refund_fee,
                    $total_fee - $refund_fee,
                    $fee_amount,
                    $remark,
                ];
            }
            fclose($f); // 关闭文件
            //处理导出逻辑
            $title = [
                "唯一", "总店ID", "订单号", "状态", "总金额", "退款金额", "实收金额", "手续费", "备注"
            ];
            //写入excel
            $util = new ExeclUtil();
            $fileName = "对账明细-通联代扣" . ($where["month"] ?? date("Y-m-d")) . "_" . time() . ".csv";
            $filePath = public_path("/uploads/csv/tl/" . date("Y/md", time()) . "/");
            if (!is_dir($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $util->exportToExcel($filePath . $fileName, [], $title, $data);
            $url = $util->uploadOss($filePath . $fileName, $fileName);
            //删除文件
            if (file_exists($filePath . $fileName)) {
                unlink($filePath . $fileName);
            }
            //删除fileName
            dump($url);
            dd("总交易金额：" . $total_fee_count, "退款金额：" . $refund_fee_count, "手续费：" . $fee_amount_count, "交易金额-退款金额:" . ($total_fee_count - $refund_fee_count), "总数：" . $num);
        } catch (\Exception $e) {
            dump($e->getMessage() . $e->getLine() . $e->getFile());
        }
    }
}
